# encoding: utf-8
"""
@author: F1233225
@file: SendMail.py
@time: 2018/9/18 下午 03:23
@desc:
"""
import os
os.environ.update({"DJANGO_SETTINGS_MODULE": "bugTracking.settings"})
from bugs.mail.Super_Notes import SuperNotes
from bugs.models import Mail
from threading import Timer
from datetime import datetime
import time

MAIL_PATH = r'C:\Program Files (x86)\Super Notes\SuperNotes.exe'
MAIL_USER = 'luke.xf.zhang@mail.foxconn.com'
MAIL_PWD = 'Asdf*963.'


def pre_send():
    while 1:
        mails = Mail.objects.filter(state=u'待发送')
        count = mails.count()
        if count > 0:
            for i, mail in enumerate(mails):
                send_mail(mail.id, mail.recipient, mail.bug_id, mail.project, mail.message)

            # count = Mail.objects.filter(state=u'待发送').count()
        time.sleep(10)


def send_mail(mail_id, recipient, bug_id, project, message):
    start_time = time.time()
    message_dict = {}
    message_dict['To'] = recipient
    message_dict['Title'] = u'Super Notes 自動化'
    if message == 'new bug':
        info = project + u'专案有新bug提交,' + u'id是：'+str(bug_id)
    else:
        info = project + u'专案' + str(bug_id) + u'号bug已修复完成'
    message_dict['Content'] = ['Dear All:', info, u'luke  /luke.xf.zhang@mail.foxconn.com/EERF-FATP SW/EXT.GL : 77875']
    supernote = SuperNotes(MAIL_PATH, MAIL_USER, MAIL_PWD)
    supernote.send_notes(message_dict)
    supernote.close()
    # 发送之后, mail状态修改为 已发送
    m = Mail.objects.get(id__exact=mail_id)
    m.state = u'已发送'
    m.save()
    end_time = time.time()
    print('time:', end_time - start_time)


def test_send_mail():
    start_time = time.time()
    print('count:', Mail.objects.all().count())
    message_dict = {}
    # message_dict['To'] = 'francis.br.chang@mail.foxconn.com'
    message_dict['To'] = 'luke.xf.zhang@mail.foxconn.com'
    message_dict['Title'] = u'Super Notes 自動化'
    message_dict['Content'] = ['Dear All:', '', u'luke  /luke.xf.zhang@mail.foxconn.com/EERF-FATP SW/EXT.GL : 77875']
    supernote = SuperNotes(MAIL_PATH, MAIL_USER, MAIL_PWD)
    supernote.send_notes(message_dict)
    supernote.close()
    end_time = time.time()
    print('time:', end_time-start_time)


def timedTask():
    '''
    第一个参数: 延迟多长时间执行任务(单位: 秒)
    第二个参数: 要执行的任务, 即函数
    第三个参数: 调用函数的参数(tuple)
    '''
    Timer(10, task, ()).start()


# 定时任务
def task():
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


if __name__ == '__main__':
    pre_send()
